package com.thread.exe;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class AdShow {
	
	private static final long TIME_BUDGET = 30;
	private final Ad DEFAULT_AD = new Ad();
	private final ExecutorService exe = Executors.newCachedThreadPool();
	
	Page renderPageWithAd() throws InterruptedException {
		long endNanos = System.nanoTime() + TIME_BUDGET;
		Future<Ad> f = exe.submit(new FetchAdTask<Ad>());
		//在等待广告的同时显示页面
		Page page = renderText();
		long timeLeft = endNanos - System.nanoTime();
		Ad ad = null;
		try {
			ad = f.get(timeLeft, TimeUnit.NANOSECONDS);
		} catch (ExecutionException e) {
			ad = DEFAULT_AD;
		} catch (TimeoutException e) {
			ad = DEFAULT_AD;
			f.cancel(true);
		}
		page.setAd(ad);
		return page;
	}
	
	private Page renderText() {
		return null;
	}

	private class Page{
		public void setAd(Ad ad) {
		}
	}
	
	private class Ad{}
	
	private class FetchAdTask<Ad> implements Callable<Ad> {
		@Override
		public Ad call() throws Exception {
			return null;
		}
	}
}


